package com.example.backend.service;

import com.example.backend.mapper.UserMapper;
import com.example.backend.model.LoginRequest;
import com.example.backend.model.User;
import com.example.backend.utils.ResponseStatus;
import com.example.backend.validate.ImageCode;
import com.example.backend.validate.ValidateStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Base64;
import java.util.Optional;
import java.util.Random;

@Service
public class UserService {
    public static final String LOGINKEY = "login-user";
    public static final String SESSION_KEY_IMAGE_CODE = "SESSION_KEY_IMAGE_CODE";

    @Autowired
    UserMapper mapper;

    public User findLoginUser(HttpSession session) {
        return (User) session.getAttribute(LOGINKEY);
    }

    public int login(LoginRequest loginRequest, HttpSession session) {
        Optional<User> matchUser = Optional.ofNullable(mapper.findByName(loginRequest.getUsername()));
        // verify validate code first
        String validateCode = loginRequest.getValidateCode();
        ValidateStatus status = validateCode(session, validateCode);
        if(status != ValidateStatus.SUCCESS) {
            return -1;
        }

        if(matchUser.isPresent()) {
            User user = matchUser.get();
            String passwordHash = loginRequest.getPasswordHash();
            String password = user.getPassword();
            String encode = new String(Base64.getEncoder().encode(password.getBytes()));

            if(passwordHash.equals(encode)) {
                session.setAttribute(LOGINKEY, user);
                return 0;
            } else {
                return -1;
            }
        } else {
            return -1;
        }
    }

    @Transactional
    public int register(User user) {
        return mapper.insertOne(user);
    }

    public int exit(User user, HttpSession session) {
        Optional<User> optionalUser = Optional.ofNullable(findLoginUser(session));
        int flag = -1;
        if(optionalUser.isPresent()) {
            session.removeAttribute(LOGINKEY);
            flag = 0;
        }

        return flag;
    }

    public void createCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        ImageCode imageCode = createImageCode();
        session.setAttribute(SESSION_KEY_IMAGE_CODE, imageCode);
        ImageIO.write(imageCode.getImage(), "jpeg", response.getOutputStream());
    }


    public ValidateStatus validateCode(HttpSession session, String validateCode) {
        ImageCode codeInSession = (ImageCode) session.getAttribute(SESSION_KEY_IMAGE_CODE);
        if(codeInSession == null) {
            throw new RuntimeException("fuck you, codeInSession is null");
        }
        String codeInImage = codeInSession.getCode();
        if(codeInSession.isExpire()) {
            return ValidateStatus.TIMEOUT;
        } else if(!validateCode.equals(codeInImage)) {
            return ValidateStatus.WRONGPASSWORD;
        } else {
            return ValidateStatus.SUCCESS;
        }

    }


    ImageCode createImageCode() {
        int width = 100;
        int height = 36;
        int length = 4;
        int expireIn = 60;

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        Random random = new Random();
        graphics.setColor(getRandColor(200, 500));
        graphics.fillRect(0, 0, width, height);
        graphics.setFont(new Font("Times New Roman", Font.ITALIC, 20));
        graphics.setColor(getRandColor(160, 200));
        for(int i = 0; i < 155; i += 1) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            graphics.drawLine(x, y, x + xl, y + yl);
        }

        StringBuilder sRand = new StringBuilder();
        for(int i = 0; i < length; i += 1) {
            String rand = String.valueOf(random.nextInt(10));
            sRand.append(rand);
            graphics.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            graphics.drawString(rand, 13 * i + 6, 16);
        }

        graphics.dispose();
        return new ImageCode(image, sRand.toString(), expireIn);
    }

    Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if(fc > 255) fc = 255;
        if(bc > 255) bc = 255;

        int bound = bc - fc;
        int r = fc + random.nextInt(bound);
        int g = fc + random.nextInt(bound);
        int b = fc + random.nextInt(bound);
        return new Color(r, g, b);

    }
}
